<template>
  <!-- 部门新增 -->
  <el-dialog
    v-dialogDrag
    v-loading="btnDisabled"
    element-loading-text="正在为您修改,请等待"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    append-to-body
    :lock-scroll="false"
    :title="initTitle"
    :visible.sync="initVisible"
    class="dialogStyleMiddle"
    :before-close="cancel"
  >
    <div style="text-align:left">
      <el-form
        ref="initEnterpriseForm"
        :model="initEnterprise"
        :rules="initRules"
        label-width="80px"
      >
        <el-row>
          <el-col :span="24"><div class="grid-content bg-purple">分公司信息</div></el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="公司名称" prop="deptName">
              <el-input v-model="initEnterprise.deptName" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24"><div class="grid-content bg-purple">分公司部门管理员角色</div></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称" prop="deptRoleName">
              <el-input v-model="initEnterprise.deptRoleName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限字符" prop="deptRoleKey">
              <el-input v-model="initEnterprise.deptRoleKey" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24"><div class="grid-content bg-purple">分公司管理员角色</div></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="initEnterprise.roleName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限字符" prop="roleKey">
              <el-input v-model="initEnterprise.roleKey" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24"><div class="grid-content bg-purple">分公司管理员信息</div></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="initEnterprise.userName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录账号" prop="loginName">
              <el-input v-model="initEnterprise.loginName" auto-complete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录密码" prop="password">
              <el-input v-model="initEnterprise.password" type="password" autocomplete="new-password" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="initEnterprise.confirmPassword" type="password" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item label="套餐选择" prop="tempId">
              <el-select v-model="initEnterprise.tempId" @change="selectTrigger">
                <el-option
                  v-for="(item,key) in templateOptiom"
                  :key="key"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form label-width="110px">
              <el-form-item label="菜单权限" class="el-tree-wrap">
                <p class="all-expand">
                  <span v-if="AddExpand" @click="unFoldAll()"><i class="el-icon-caret-bottom" />全部展开</span>
                  <span v-else @click="closeAll()"><i class="el-icon-caret-top" />全部关闭</span>
                </p>
                <div class="el-tree-cont">
                  <el-tree
                    v-show="openOrNot"
                    ref="menu"
                    :data="menuOptions"
                    show-checkbox
                    node-key="id"
                    empty-text="加载中，请稍后"
                    :props="defaultProps"
                    :default-expand-all="defaultExpand"
                    :highlight-current="true"
                    :render-content="renderContent"
                    @check="handleChange"
                  />
                </div>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="medium" @click="cancel">取 消</el-button>
      <el-button v-clickForbidden size="medium" type="primary" @click="submitForm('initEnterpriseForm')">保 存</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addInitDept } from '@/api/system/dept'
import { selectTreeById } from '@/api/enterprise/company-temp'
import { selectTreeMenuAll } from '@/api/system-tool/menu'
// 企业套餐list方法
import { getCompTemp } from '@/api/enterprise/company-temp'
export default {
  data() {
    var checkLoginName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('登录账号不能为空'))
      } else if (value.length < 2) {
        return callback(new Error('登录账号长度不能小于2位'))
      } else if (value.length > 20) {
        return callback(new Error('登录账号长度不能大于20位'))
      } else {
        // var userId = ''
        // var loginName = value
        // checkLoginNameUnique(userId, loginName).then(res => {
        //   if (res.code !== 0) {
        //     return callback(new Error('登录名称已经存在'))
        //   } else {
        //     }
        callback()
      }
    }
    var validUserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名称不能为空'))
      } else if (value.length < 2) {
        return callback(new Error('用户名称长度不能小于2位'))
      } else if (value.length > 20) {
        return callback(new Error('用户名称长度不能大于20位'))
      } else {
        callback()
      }
    }
    var validPassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('密码不能为空'))
      } else if (value.length < 6) {
        return callback(new Error('密码长度不能小于6位'))
      } else if (value.length > 20) {
        return callback(new Error('密码长度不能大于20位'))
      } else {
        callback()
      }
    }
    var checkConfirmPassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('确认密码不能为空'))
      } else if (value !== this.initEnterprise.password) {
        return callback(new Error('确认密码与登录密码不一致'))
      } else {
        callback()
      }
    }
    // 权限字符查询重复
    var checkDeptRoleKey = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('权限字符不能为空'))
      } else if (value === this.initEnterprise.roleKey) {
        return callback(new Error('权限字符已经存在'))
      } else {
        callback()
      }
    }
    // 权限字符查询重复
    var checkroleKey = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('权限字符不能为空'))
      } else if (value === this.initEnterprise.deptRoleKey) {
        return callback(new Error('权限字符已经存在'))
      } else {
        callback()
      }
    }
    // 角色名称查询重复
    var checkDeptRoleName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('角色名称不能为空'))
      } else if (value === this.initEnterprise.roleName) {
        return callback(new Error('角色名称已经存在'))
      } else {
        callback()
      }
    }
    // 角色名称查询重复
    var checkRoleName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('角色名称不能为空'))
      } else if (value === this.initEnterprise.deptRoleName) {
        return callback(new Error('角色名称已经存在'))
      } else {
        callback()
      }
    }
    return {
      defaultExpand: true,
      // 模板名称
      templateOptiom: [],
      // 初始化内容标题
      initTitle: '',
      initVisible: false,
      // 保存按钮是否禁用
      btnDisabled: false,
      // 初始化from表单
      initEnterprise: {
        // 企业id
        enterpriseId: '',
        // 分公司id
        subCompany: '',
        // 部门id
        deptId: '',
        // 部门名称
        deptName: '',
        // 部门管理员名称
        deptRoleName: '',
        // 权限字符
        deptRoleKey: '',
        roleName: '',
        roleKey: '',
        userName: '',
        loginName: '',
        password: '',
        confirmPassword: '',
        // 企业套餐id
        tempId: '',
        menuIds: []
      },
      initRules: {
        userName: [
          { required: true, validator: validUserName, trigger: 'blur' }
        ],
        loginName: [
          { required: true, validator: checkLoginName, trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validPassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: checkConfirmPassword, trigger: 'blur' }
        ],
        deptRoleName: [{ required: true, validator: checkDeptRoleName, trigger: 'blur' }],
        deptRoleKey: [{ required: true, validator: checkDeptRoleKey, trigger: 'blur' }],
        roleName: [{ required: true, validator: checkRoleName, trigger: 'blur' }],
        roleKey: [{ required: true, validator: checkroleKey, trigger: 'blur' }],
        tempId: [{ required: true, message: '分公司套餐不能为空', trigger: 'blur' }]
      },
      openOrNot: false,
      AddExpand: true,
      // 树形菜单数据
      menuOptions: [],
      // 加载树形菜单结构
      defaultProps: {
        children: 'children',
        label: 'label',
        disabled: this.disabledFn
      }
    }
  },
  methods: {
    // 菜单树节点加载 设置菜单后面是否显示“数据权限”字样
    renderContent(h, { node, data, checked, store }) {
      // 判断菜单类型
      const menuType = data.menuType
      // 判断节点是否选中
      var isNodeCheck = false
      /** 当节点是选中状态时显示数据权限
       * 当节点是半选中状态时也显示数据权限
       */
      if (node.checked) {
        isNodeCheck = true
      } else {
        /** 获取次节点下面的子节点
         * 当子节点其中也有选择状态时设置isNodeCheck = true
         * 并且跳出循环
         */
        const childNodes = node.childNodes
        for (var i = 0; i < childNodes.length; i++) {
          if (childNodes[i].checked) {
            isNodeCheck = true
            break
          }
        }
      }
      /**
       * 当菜单类型为菜单（C）时 并且 次菜单是选中状态或者半选中状态
       * 则显示“数据权限”字样
       */
      if (menuType === 'C' && isNodeCheck) {
        return (
          <span class='custom-tree-node'>
            <span>{node.label}</span>
            <span style='margin-left:20px'>
              <el-button
                size='mini'
                type='text'
                on-click={() => this.append(data, event)}
              >
                数据权限
              </el-button>
            </span>
          </span>
        )
      } else {
        return (
          <span class='custom-tree-node'>
            <span>{node.label}</span>
          </span>
        )
      }
    },
    // 当复选框选中状态改变时
    handleChange(data, nodefunction) {
      var _this = this
      // 定义变量用于判断当前节点有没有选择
      var isMenuId = true
      // 当天节点改变状态的值
      var menuId = data.menuId
      // 获取数组中被选中节点的值
      var checkedKeys = nodefunction.checkedKeys
      // 当前节点是选中状态标识设置为false
      for (var i = 0; i < checkedKeys.length; i++) {
        if (menuId === checkedKeys[i]) {
          isMenuId = false
        }
      }
      // 默认数据权限
      const defauleDataScopList = _this.defauleDataScopList
      // isMenuId 为 true时 表示该节点没有被选中
      if (isMenuId && data.menuType === 'C') {
        // 当前节点没有被选中,遍历树 把该节点的数据权限设为默认数据权限
        _this.changeMenuOptions(menuId, defauleDataScopList)
      } else if (isMenuId && data.menuType === 'M') {
        // 当目录节点没有被选中, 遍历树下面的菜单节点，设置为默认数据权限
        const dataMenuIds = _this.getMenuIdFilter().filter(data)
        for (var j = 0; j < dataMenuIds.length; j++) {
          _this.changeMenuOptions(dataMenuIds[j], defauleDataScopList)
        }
      } else if (isMenuId && data.menuType === 'F') {
        /* 当前节点没有选中 ，且节点是“按钮类型”,判断该节点的父节点是否是半选状态，
         * 父节点不是半选状态 且父节点是“菜单类型” 设置 父节点的数据权限为默认数据权限
         */
        // 获取该节点的父节点
        const dataParentId = data.parentId
        const halfCheckedKeys = nodefunction.halfCheckedKeys
        // 定义变量记录父节点是否是半选状态
        var isParentIdHalf = true
        for (var K = 0; K < halfCheckedKeys.length; K++) {
          if (dataParentId === halfCheckedKeys[K]) {
            // 当父节点是半选状态则 改为false
            isParentIdHalf = false
          }
        }
        if (isParentIdHalf) {
          // 父节点没有被选中,遍历树 把该节点的数据权限设为默认数据权限
          _this.changeMenuOptions(dataParentId, defauleDataScopList)
        }
      }
    },
    // 全部展开
    unFoldAll() {
      console.log(this.$refs.menu)
      this.treeSelected = this.$refs.menu.getCheckedKeys().concat(this.$refs.menu.getHalfCheckedKeys())
      this.AddExpand = false
      this.defaultExpand = true
      this.openOrNot = false
      setTimeout(() => {
        this.openOrNot = true
        this.$nextTick(() => {
          this.$refs.menu.setCheckedKeys(this.treeSelected)
        })
      }, 10)
    },
    // 全部关闭
    closeAll() {
      this.treeSelected = this.$refs.menu.getCheckedKeys().concat(this.$refs.menu.getHalfCheckedKeys())
      this.AddExpand = true
      this.defaultExpand = false
      this.openOrNot = false
      setTimeout(() => {
        this.openOrNot = true
        this.$nextTick(() => {
          this.$refs.menu.setCheckedKeys(this.treeSelected)
        })
      }, 10)
    },
    // 初始化添加页面
    addFrom(enterpriseId, deptName, subCompany) {
      this.empetyInitEnterprise()
      this.getMenuTreeData()
      this.initEnterprise.enterpriseId = enterpriseId
      this.initEnterprise.deptName = deptName
      this.initEnterprise.subCompany = subCompany
      this.$nextTick(() => {
        this.getComTempList(this.initEnterprise.enterpriseId, this.initEnterprise.subCompany)
      })
      this.initTitle = '分公司初始化'
      this.initVisible = true
      this.handleInput(deptName)
    },
    // 自动生成角色和权限标识
    handleInput(val) {
      const pinyin = require('pinyin')
      let a = pinyin(val, {
        style: pinyin.STYLE_FIRST_LETTER
      })
      a = a.join('')
      // 转大写
      a = a.toUpperCase()
      console.log(a.toUpperCase(), 222) // ['g']
      this.initEnterprise.deptRoleName = val + '分公司部门管理员'
      this.initEnterprise.deptRoleKey = a + '_DEPT'
    },
    // 清空菜单树
    resetChecked() {
      this.$refs.menu.setCheckedKeys([])
    },
    // 菜单树禁用
    disabledFn(data, node) {
      if (data !== null) {
        // 根据自己的节点数据条件设置判断，我只提供了个参考
        return true
      } else {
        return false
      }
    },
    // 清空初始化表单
    empetyInitEnterprise() {
      this.initEnterprise = {
        // 企业id
        enterpriseId: '',
        // 分公司id
        subCompany: '',
        // 部门id
        // deptId: "",
        // 部门名称
        deptName: '',
        // 部门管理员名称
        deptRoleName: '',
        // 权限字符
        deptRoleKey: '',
        roleName: '',
        roleKey: '',
        userName: '',
        loginName: '',
        password: '',
        tempId: '',
        menuIds: []
      }
      this.resetForm('initEnterpriseForm')
    },
    // 树形菜单加载
    getMenuTreeData() {
      var _this = this
      selectTreeMenuAll().then(resp => {
        if (resp) {
          _this.menuOptions = resp.data
        }
      })
    },
    // 部门编码改变时改变部门编码长度字段
    changRuleLength(val) {
      if (val != null && val !== '') {
        this.initEnterprise.ruleLength = val.length
      }
    },

    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getHalfCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 弹框取消按钮
    cancel() {
      // this.resetChecked()
      this.initVisible = false
      this.btnDisabled = false
      this.empetyInitEnterprise()
    },
    submitForm(fromData) {
      var _this = this
      this.$refs[fromData].validate(valid => {
        if (valid) {
          this.initEnterprise.menuIds = this.getMenuAllCheckedKeys()
          this.btnDisabled = true
          addInitDept(this.initEnterprise).then(resp => {
            if (resp) {
              this.btnDisabled = false
              _this.initVisible = false
              this.msgSuccess('初始化成功!')
              _this.empetyInitEnterprise()
              this.resetChecked()
            } else {
              this.btnDisabled = false
            }
          }).catch(() => {
            this.btnDisabled = false
          })
        }
      })
    },
    // 获取企业套餐
    getComTempList(enterpriseId, subCompany) {
      getCompTemp({ enterpriseId: enterpriseId, subCompany: subCompany }).then(resp => {
        if (resp) {
          this.templateOptiom = resp.data.rows
        } else {
          this.msgError(resp.message)
        }
      })
    },
    // 套餐类型改变触发的事件
    selectTrigger(id) {
      this.$refs.menu.setCheckedKeys([])
      this.selectMenuIdsbyId(id)
    },
    // 根据企业套餐id查询菜单树menuIds[]
    selectMenuIdsbyId(id) {
      selectTreeById(id).then(resp => {
        if (resp) {
          var menuIds = resp.data
          this.$refs.menu.setCheckedKeys(menuIds)
        }
      })
    }
  }
}
</script>
<style scoped>
  .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
    background-color: #409eff;
    border-color: #dcdfe6;
  }
  .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
    border-color: #4068ff;
  }
</style>
